<template>
  <div class="app-container">
    <div class="filter-container">
      <el-form ref="listQuery" :rules="rules" :model="listQuery" :inline="true" label-position="left" label-width="80px">
        <el-form-item label="机构名称">
          <el-input v-model="listQuery.name" placeholder="机构名称" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter" />
        </el-form-item>
        <el-form-item label="机构编码">
          <el-input v-model="listQuery.code" placeholder="机构编码" class="filter-item" @keyup.enter.native="handleFilter" />
        </el-form-item>
        <el-form-item label="机构类型">
          <el-select v-model="listQuery.type" clearable filterable placeholder="机构类型" style="width:100%">
            <el-option
              v-for="item in orgTypeData"
              :key="item.value"
              :label="item.value"
              :value="item.code"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button-group>
            <el-button v-waves type="primary" class="filter-item" icon="el-icon-search" @click="handleFilter">查询</el-button>
            <el-button class="filter-item" icon="el-icon-refresh" @click="resetQuery">重置</el-button>
          </el-button-group>
        </el-form-item>
        <el-form-item>
          <el-button class="filter-item" type="primary" icon="el-icon-plus" @click="handleCreate">
            新增
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      row-key="id"
      default-expand-all
      :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
      style="width: 100%;"
    >
      <el-table-column prop="name" align="center" label="机构名称" />
      <el-table-column prop="code" align="center" label="机构编码" />
      <el-table-column prop="level" align="center" label="级别" width="70" />
      <el-table-column prop="type" align="center" label="机构类型" :formatter="typeFilter" />
      <el-table-column prop="orderNo" align="center" label="排序" width="100" />
      <el-table-column align="center" label="状态" class-name="status-col" width="70">
        <template slot-scope="{row}">
          <el-tag v-if="row.status === 1" type="success">启用</el-tag>
          <el-tag v-else type="danger">禁用</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="修改时间" width="160" align="center" />
      <el-table-column prop="remark" label="备注" header-align="center" />
      <el-table-column label="操作" align="center" width="200" class-name="small-padding fixed-width">
        <template slot-scope="{row}">
          <el-button type="primary" icon="el-icon-edit" size="mini" @click="handleUpdate(row)">
            编辑
          </el-button>
          <el-button icon="el-icon-delete" size="mini" @click="handleDelete(row)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="right" label-width="90px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="上级机构" prop="pid">
              <el-cascader
                id="orgId"
                v-model="temp.pid"
                :options="list"
                :props="{ checkStrictly: true, emitPath: false, value: 'id', label: 'name', expandTrigger: 'hover' }"
                placeholder="请选择上级机构"
                clearable
                style="width:100%"
              >
                <template slot-scope="{ node, data }">
                  <span>{{ data.name }}</span>
                  <span v-if="!node.isLeaf"> ({{ data.children.length }}) </span>
                </template>
              </el-cascader>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="机构名称" prop="name">
              <el-input id="name" v-model="temp.name" placeholder="请输入机构名称" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="机构编码" prop="code">
              <el-input id="code" v-model="temp.code" placeholder="请输入机构编码" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="级别">
              <el-input-number v-model="temp.level" :min="1" :max="100" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="机构类型">
              <el-select v-model="temp.type" clearable filterable placeholder="机构类型" style="width:100%">
                <el-option
                  v-for="item in orgTypeData"
                  :key="item.value"
                  :label="item.value"
                  :value="item.code"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="排序">
              <el-input-number v-model="temp.orderNo" :min="1" :max="100" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态">
              <el-radio-group v-model="temp.status">
                <el-radio :label="1">
                  启用
                </el-radio>
                <el-radio :label="2">
                  禁用
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注">
              <el-input v-model="temp.remark" :autosize="{ minRows: 2, maxRows: 4}" type="textarea" placeholder="请输入备注" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取 消
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          确 定
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { orgTypeList, sysOrgList, addOrg, deleteOrg, updateOrg } from '@/api/org'
import waves from '@/directive/waves' // waves directive

export default {
  name: 'SysOrg',
  directives: { waves },
  data() {
    return {
      tableKey: 0,
      list: [],
      listLoading: true,
      listQuery: {
        name: undefined,
        code: undefined,
        type: undefined
      },
      temp: {
        id: undefined,
        name: '',
        code: '',
        orderNo: 100,
        status: 1,
        remark: ''
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑机构',
        create: '添加机构'
      },
      rules: {
        name: [{ required: true, message: '机构名称不能为空', trigger: 'blur' }],
        code: [{ required: true, message: '机构编码不能为空', trigger: 'blur' }]
      },
      orgTypeData: []
    }
  },
  created() {
    this.getList()
    this.getOrgTypes()
  },
  methods: {
    getList() {
      this.listLoading = true
      sysOrgList(this.listQuery).then(response => {
        this.listLoading = false
        this.list = response.result
      })
    },
    async getOrgTypes() {
      const res = await orgTypeList()
      this.orgTypeData = res.result ?? []
    },
    handleFilter() {
      this.getList()
    },
    typeFilter(row, column, cellValue, index) {
      return this.orgTypeData.find(u => u.code === cellValue)?.value
    },
    resetQuery() {
      this.listQuery.name = ''
      this.listQuery.code = ''
      this.listQuery.type = ''
      this.getList()
    },
    resetTemp() {
      this.temp = {
        id: undefined,
        remark: '',
        name: '',
        status: undefined,
        code: ''
      }
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          addOrg(tempData).then(() => {
            // this.list.unshift(tempData)
            this.getList()
            this.dialogFormVisible = false
            this.$notify({
              title: 'Success',
              message: '新增机构成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    async handleUpdate(row) {
      this.temp = Object.assign({}, row) // copy obj
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          updateOrg(tempData).then(() => {
            this.getList()
            this.dialogFormVisible = false
            this.$notify({
              message: '编辑机构成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleDelete(row) {
      this.$confirm('确定删除机构吗?', '提示信息', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async() => {
          await deleteOrg(row.id)
          this.getList()
          this.$message({
            type: 'success',
            message: '删除机构成功!'
          })
        })
        .catch(err => { console.error(err) })
    }
  }
}
</script>

  <style scoped>
  .filter-container .el-form-item{
      margin-bottom: auto;
  }
  </style>

